package com.wmh.baseservice.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.*;
import com.wmh.baseservice.system.pojo.SysMessage;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysMessageService;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.pojo.*;
import com.wmh.baseservice.user.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 青石
 */
@ApiIgnore
@RestController
@RequestMapping("dev")
public class AdDevController {

    @Resource
    SysParamsService sysParamsService;

    @Resource
    UsInfoService usInfoService;

    @Resource
    UsActivityRegisterService usActivityRegisterService;
    @Resource
    UsAddressService usAddressService;
    @Resource
    UsAfterSaleApplyService usAfterSaleApplyService;
    @Resource
    UsEvaluateService usEvaluateService;
    @Resource
    UsGoodsOrderService usGoodsOrderService;
    @Resource
    UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    UsIncomeExpendService usIncomeExpendService;
    @Resource
    UsJoinApplyService usJoinApplyService;
    @Resource
    UsRentOrderService usRentOrderService;
    @Resource
    UsShopCarService usShopCarService;
    @Resource
    UsTopUpWithdrawalService usTopUpWithdrawalService;
    @Resource
    UsVegetableOrderService usVegetableOrderService;

    @Resource
    MerchantActivityService merchantActivityService;
    @Resource
    MerchantApplyService merchantApplyService;
    @Resource
    MerchantBankCardService merchantBankCardService;
    @Resource
    MerchantFreightTemplateService merchantFreightTemplateService;
    @Resource
    MerchantGoodsService merchantGoodsService;
    @Resource
    MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    MerchantIncomeExpendService merchantIncomeExpendService;
    @Resource
    MerchantInfoService merchantInfoService;
    @Resource
    MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    MerchantPlotRentService merchantPlotRentService;
    @Resource
    MerchantRolePermissionsService merchantRolePermissionsService;
    @Resource
    MerchantVegetableService merchantVegetableService;
    @Resource
    private SysMessageService sysMessageService;



    @PostMapping("public/clearingUserTraces")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"usId", "nickName"})
    @Transactional(rollbackFor = Exception.class)
    public String clearingUserTraces(Long usId, String nickName) {
        SysParams sysParams = sysParamsService.getById(18);
        if (sysParams == null) {
            return ReturnBody.error("获取系统参数失败");
        }
        String[] nickNames = sysParams.getValue().split(",");
        if (Arrays.stream(nickNames).noneMatch(e -> e.equals(nickName))) {
            return ReturnBody.error("不支持清除的用户昵称");
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (usInfo == null) {
            return ReturnBody.error("不存在的用户 ID");
        }
        if (!nickName.equals(usInfo.getNick())) {
            return ReturnBody.error("用户ID 与 实际删除昵称不符合");
        }

        /* 删除失败的表 */
        ArrayList<String> failTable = new ArrayList<>();
        if (!usActivityRegisterService.remove(new QueryWrapper<UsActivityRegister>()
                .eq(UsActivityRegister.US_ID, usInfo.getId())
        )) {
            failTable.add("用户活动报名记录 | us_activity_register");
        }
        if (!usAddressService.remove(new QueryWrapper<UsAddress>()
                .eq(UsAddress.US_ID, usInfo.getId()))) {
            failTable.add("用户地址信息 | us_address");
        }
        if (!usAfterSaleApplyService.remove(new QueryWrapper<UsAfterSaleApply>()
                .eq(UsAfterSaleApply.US_ID, usInfo.getId()))) {
            failTable.add("用户售后申请记录 | us_after_sale_apply");
        }
        if (!usEvaluateService.remove(new QueryWrapper<UsEvaluate>()
                .eq(UsEvaluate.US_ID, usInfo.getId()))) {
            failTable.add("用户评价路径 | usEvaluateService");
        }
        if (!usGoodsOrderService.remove(new QueryWrapper<UsGoodsOrder>()
                .eq(UsGoodsOrder.US_ID, usInfo.getId()))) {
            failTable.add("用户订单记录 | us_goods_order");
        }
        if (!usGroupGoodsOrderService.remove(new QueryWrapper<UsGroupGoodsOrder>()
                .eq(UsGroupGoodsOrder.US_ID, usInfo.getId()))) {
            failTable.add("用户团购订单记录 | us_group_goods_order");
        }
        if (!usIncomeExpendService.remove(new QueryWrapper<UsIncomeExpend>()
                .eq(UsIncomeExpend.US_ID, usInfo.getId()))) {
            failTable.add("用户收支流水表 | us_income_expend");
        }
        if (!usJoinApplyService.remove(new QueryWrapper<UsJoinApply>()
                .eq(UsJoinApply.US_ID, usInfo.getId()))) {
            failTable.add("用户加盟申请表 | us_join_apply");
        }
        if (!usRentOrderService.remove(new QueryWrapper<UsRentOrder>()
                .eq(UsRentOrder.US_ID, usInfo.getId()))) {
            failTable.add("用户租赁订单表 | us_rent_order");
        }
        if (!usShopCarService.remove(new QueryWrapper<UsShopCar>()
                .eq(UsShopCar.US_ID, usInfo.getId()))) {
            failTable.add("用户购物车表 | us_shop_car");
        }
        if (!usTopUpWithdrawalService.remove(new QueryWrapper<UsTopUpWithdrawal>()
                .eq(UsTopUpWithdrawal.US_ID, usInfo.getId()))) {
            failTable.add("用户充值/提现表 | us_top_up_withdrawal");
        }
        if (!usVegetableOrderService.remove(new QueryWrapper<UsVegetableOrder>()
                .eq(UsVegetableOrder.US_ID, usInfo.getId()))) {
            failTable.add("用户采摘/种植 订单表 | us_vegetable_order");
        }
        if (!sysMessageService.remove(new QueryWrapper<SysMessage>().eq(SysMessage.US_ID,usId))) {
            failTable.add("消息 | us_vegetable_order");
        }

        /* 如果是商家删除商家信息 */
        Long merchantId = usInfo.getMerchantId();
        if (merchantId != null) {
            if (!sysMessageService.remove(new QueryWrapper<SysMessage>().eq(SysMessage.MERCHANT_ID,merchantId))) {
                failTable.add("消息 | us_vegetable_order");
            }
            if (!merchantActivityService.remove(new QueryWrapper<MerchantActivity>()
                    .eq(MerchantActivity.MERCHANT_ID, merchantId))) {
                failTable.add("商家活动表 | merchant_activity");
            }
            if (!merchantApplyService.remove(new QueryWrapper<MerchantApply>()
                    .eq(MerchantApply.MERCHANT_ID, merchantId))) {
                failTable.add("商家提现申请表 | merchant_apply");
            }
            if (!merchantBankCardService.remove(new QueryWrapper<MerchantBankCard>()
                    .eq(MerchantBankCard.MERCHANT_ID, merchantId))) {
                failTable.add("商家银行卡表 | merchant_bank_card");
            }
            if (!merchantFreightTemplateService.remove(new QueryWrapper<MerchantFreightTemplate>()
                    .eq(MerchantFreightTemplate.MERCHANT_ID, merchantId))) {
                failTable.add("商家运费模板表 | merchant_freight_template");
            }
            if (!merchantGoodsService.remove(new QueryWrapper<MerchantGoods>()
                    .eq(MerchantGoods.MERCHANT_ID, merchantId))) {
                failTable.add("平台商品表 | merchant_goods");
            }

            LocalDateTime now = LocalDateTime.now();
            List<MerchantGroupGoods> list = merchantGroupGoodsService.list(
                    new QueryWrapper<MerchantGroupGoods>()
                            .eq(MerchantGroupGoods.MERCHANT_ID, merchantId)
                    .le(MerchantGroupGoods.START_TIME,now)
                    .ge(MerchantGroupGoods.END_TIME,now)
            );
            /* 清除 正在拼团的商品 redis */
            list.forEach(item -> {
                merchantGroupGoodsService.removeGroupGoodsOverTiming(item);
            });
            if (!merchantGroupGoodsService.remove(new QueryWrapper<MerchantGroupGoods>()
                    .eq(MerchantGroupGoods.MERCHANT_ID, merchantId))) {
                failTable.add("商家团购商品表 | merchant_group_goods");
            }
            if (!merchantIncomeExpendService.remove(new QueryWrapper<MerchantIncomeExpend>()
                    .eq(MerchantIncomeExpend.MERCHANT_ID, merchantId))) {
                failTable.add("商家收支流水表 | merchant_income_expend");
            }
            if (!merchantInfoService.remove(new QueryWrapper<MerchantInfo>()
                    .eq(MerchantInfo.ID, merchantId))) {
                failTable.add("商家信息表 | merchant_info");
            }
            if (!merchantPlotRegionService.remove(new QueryWrapper<MerchantPlotRegion>()
                    .eq(MerchantPlotRegion.MERCHANT_ID, merchantId))) {
                failTable.add("商家菜/果地分区表 | merchant_plot_region");
            }
            if (!merchantPlotRentService.remove(new QueryWrapper<MerchantPlotRent>()
                    .eq(MerchantPlotRent.RENT_MERCHANT_ID, merchantId))) {
                failTable.add("商家菜/果地租赁表 | merchant_plot_rent");
            }
            if (!merchantRolePermissionsService.remove(new QueryWrapper<MerchantRolePermissions>()
                    .eq(MerchantRolePermissions.MERCHANT_ID, merchantId))) {
                failTable.add("商家角色权限表 | merchant_role_permissions");
            }
            if (!merchantVegetableService.remove(new QueryWrapper<MerchantVegetable>()
                    .eq(MerchantVegetable.MERCHANT_ID, merchantId))) {
                failTable.add("商家蔬菜(产品)表 | merchant_vegetable");
            }
            /* 清除商家ID */
            usInfoService.updateById(usInfo.setMerchantId(null).setInviteId(-1L));
            if (usInfoService.update(new UpdateWrapper<UsInfo>().eq(UsInfo.INVITE_ID,usId).set(UsInfo.INVITE_ID,-1))) {
                failTable.add("用户邀请 | merchant_role_permissions");
            }
        }
        return ReturnBody.success(failTable);
    }
}
